#!/usr/bin/lua
require("lua-xwrt.addon.uci")
require("lua-xwrt.addon.string")

    local user_str = ""
    local sep = ""

	local users_chk = uci.get_all("freeradius_check")
	local users_rpl = uci.get_all("freeradius_reply")

	for name, tdata in pairs(users_chk) do
		if name ~= "default" then
			local checks = users_chk[name]
			local replys = users_rpl[name]
			user_str = user_str .. "\n\n"..name
			sep = "\t"
			for j, k in pairs(checks) do
				if not string.match(j,"[.]") then
					if string.trim(j) == "User_Password" then
						user_str = user_str..sep.. string.gsub(j,"_","-").." := \""..k.."\""
					else
						user_str = user_str..sep.. string.gsub(j,"_","-").." := "..tostring(k)
					end
					sep = ", "
				end
			end
			sep = "\n\t"
			for j, k in pairs(replys) do
				if not string.match(j,"[.]") then
					user_str = user_str..sep.. string.gsub(j,"_","-").." = "..tostring(k)
					sep = ", "
				end
			end
		end
    end
    sep = ""
    user_str = user_str.."\n\nDEFAULT\t"
	for i, v in pairs (users_chk.default) do
		if not string.match(i,"[.]") then
			user_str = user_str..sep..string.gsub(i,"_","-").." := "..tostring(v)
			sep = ", "
		end
	end
    sep = "\n\t"
    for i, v in pairs (users_rpl.default) do
		if not string.match(i,"[.]") then
			user_str = user_str..sep..string.gsub(i,"_","-").." = "..tostring(v)
			sep = ",\n\t"
		end
	end
    local pepe = io.open("/etc/freeradius2/users","w")
    pepe:write(user_str)
    pepe:close()
